package com.minivision.sdktestdemo.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.astuetz.PagerSlidingTabStrip;
import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.controler.ui.viewpager.MusicNavControler;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.event.PlayMusicEvent;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MusicNavFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MusicNavFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MusicNavFragment extends Fragment implements OnFragmentUpdatedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private int mCols;

    public MusicNavFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param cols   Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MusicNavFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MusicNavFragment newInstance(int cols, String param2) {
        MusicNavFragment fragment = new MusicNavFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mCols = getArguments().getInt(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        Log.i("MusicNavFragment", "onCreate: ");
        //EventBus.getDefault().register(this);
    }

    @Bind(R.id.pager_sliding_tab_strip)
    PagerSlidingTabStrip mPagerSlidingTabStrip;

    @Bind(R.id.vg_music_nav)
    ViewPager mViewPager;

    private PlayMusicEvent mEvent;

    private MusicNavAdapter mMusicNavAdapter;

    private ToolBarHelper mHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_music_nav, container, false);
        ButterKnife.bind(this, view);
        initData();
        initView();
//        setHasOptionsMenu(true);
        Log.i("MusicNavFragment", "onCreateView: ");
        return view;
    }

    private MusicNavControler mMusicNavControler;

    private void initData() {
        mMusicNavControler = mMusicNavControler == null ? new MusicNavControler(getActivity()) : mMusicNavControler;
        List<Fragment> list = mMusicNavControler.getViewPagerFragments();
        //这里要主要,必须用getChildFragmentManager,否则在当前fragment在destroyview时,重新createview的时候,viewpager的fragment的内容就是空的了
        mMusicNavAdapter = mMusicNavAdapter == null ?
                new MusicNavAdapter(getChildFragmentManager(), mMusicNavControler) : mMusicNavAdapter;
    }

    private Toolbar.OnMenuItemClickListener mOnMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            boolean flag = false;
            switch (item.getItemId()) {
                default:
                    break;
            }
            return flag;
        }
    };

    private void initView() {
        mViewPager.setAdapter(mMusicNavAdapter);
        mViewPager.setOffscreenPageLimit(3);
        //必须要在setViewPager之前设置选中的文本颜色
        //mPagerSlidingTabStrip.setSelectedTabTextColor(getResources().getColor(R.color.colorPrimary));
        mPagerSlidingTabStrip.setViewPager(mViewPager);
        mPagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) mMusicNavAdapter.getItem(position);
                listener.setPlayEvent(mEvent);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onDestroyView() {
        Log.i("MusicNavFragment", "onDestroyView: ");
        //EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    @Override
    public void update(PlayMusicEvent event) {
        setPlayEvent(event);
        OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) mMusicNavAdapter.getItem(mViewPager.getCurrentItem());
        listener.update(event);
    }

    @Override
    public void update(DataModificationEvent event) {
        OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) mMusicNavAdapter.getItem(mViewPager.getCurrentItem());
        listener.update(event);
    }

    public interface ToolBarHelper {
        Toolbar getToolbar();
    }

    @Override
    public void setPlayEvent(PlayMusicEvent event) {
        if (mEvent == null) {
            mEvent = event;
        } else {
            mEvent.setPlayEvent(event);
        }
    }

    public static class MusicNavAdapter extends FragmentStatePagerAdapter {
        private MusicNavControler mMusicNavControler;

        public MusicNavAdapter(FragmentManager fm, MusicNavControler controler) {
            super(fm);
            mMusicNavControler = controler;
        }

        @Override
        public Fragment getItem(int position) {
            return mMusicNavControler.getViewPagerFragment(position);
        }

        @Override
        public int getCount() {
            return mMusicNavControler.getViewPagerSize();
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return mMusicNavControler.getTitle(position);
        }
    }

    @Override
    public void onAttach(Context context) {
        mHelper = (ToolBarHelper) context;
        super.onAttach(context);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDetach() {
        mHelper = null;
        super.onDetach();
    }
}
